package com.meihua.workflow.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.jwt.JWTUtil;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.meihua.workflow.constants.Constants;
import com.meihua.workflow.exception.BizException;
import com.meihua.workflow.mapper.SysUserMapper;
import com.meihua.workflow.mapper.SysUserRoleMapper;
import com.meihua.workflow.model.SysUser;
import com.meihua.workflow.model.SysUserRole;
import com.meihua.workflow.model.vo.UserVo;
import com.meihua.workflow.service.SysUserRoleService;
import com.meihua.workflow.service.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author maheqiang
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2023-09-25 10:30:25
*/
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>
    implements SysUserService {
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Override
    public UserVo getUserInfo(String userId) {
        UserVo userVo = new UserVo();
        BeanUtil.copyProperties(this.baseMapper.selectById(userId),userVo);
        List<String> userRole = this.sysUserRoleMapper.getUserRole(userId);
        userVo.setRoles(userRole);
        return userVo ;
    }

    @Override
    public String login(String username, String password) {
        LambdaQueryWrapper<SysUser> eq = new LambdaQueryWrapper<SysUser>().eq(SysUser::getUsername, username).eq( SysUser::getPassword, password);
        SysUser sysUser = this.baseMapper.selectOne(eq);
        if (BeanUtil.isEmpty(sysUser)){
            throw new BizException("用户名或密码错误");
        }
        StpUtil.login(sysUser.getUserId());
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("user_id", sysUser.getUserId());
                put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60);
                put("refresh_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);
            }
        };
        return JWTUtil.createToken(map, Constants.KEY_CONSTANTS.getBytes(StandardCharsets.UTF_8));
    }

}




